package ldk.util.scrollviews

import android.content.Context
import android.util.AttributeSet
import android.widget.FrameLayout

/**
 * 可记忆性的FrameLayout
 * 记忆最大的高度值
 * Created by ldkxingzhe@163.com on 2017/9/21.
 */
open class MemoryFrameLayout: FrameLayout {
    companion object {
        private val TAG = "MemoryFrameLayout"
    }

    constructor(context: Context?) : super(context)
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val widthMode = MeasureSpec.getMode(widthMeasureSpec)
        val heightMode = MeasureSpec.getMode(heightMeasureSpec)
        if (widthMode != MeasureSpec.EXACTLY || heightMode != MeasureSpec.EXACTLY){
            throw IllegalStateException("MemoryFrameLayout only support Mode EXACTLY")
        }
        val oldMeasuredWidth = measuredWidth
        val oldMeasuredHeight = measuredHeight
        val newWidthSize = MeasureSpec.getSize(widthMeasureSpec)
        val newHeightSize = MeasureSpec.getSize(heightMeasureSpec)
        val widthSize = Math.max(oldMeasuredWidth, newWidthSize)
        val heightSize = Math.max(oldMeasuredHeight, newHeightSize)
        setMeasuredDimension(newWidthSize, newHeightSize)
        val newWidthMeasureSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY)
        val newHeightMeasureSpec = MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.EXACTLY)
        (0 until childCount)
                .map { getChildAt(it) }
                .forEach { it.measure(newWidthMeasureSpec, newHeightMeasureSpec) }
    }
}